const express = require('express')
const router = express()
const cheerio = require('cheerio')
const iconv = require("iconv-lite");
const util =require('../../util/acfunutil') ;
var AV = require('leanengine');
var Chart = AV.Object.extend('Chart');

router.get('/', (req, res) => {
    var url = req.query.url || 'http://www.officialcharts.com/charts/uk-top-40-singles-chart/';
    util.service.get(url).then(resp=>{
        const $  = cheerio.load(resp.data,{decodeEntities: false});
        var chartId = $('#this-chart-id').val();
        var chartType = $('#this-chart-type').val();
        var prev ='http://www.officialcharts.com'+$('.prev').attr('href');
        var next ='http://www.officialcharts.com'+$('.next').attr('href');
        var charts = [];
        $('.position').each((i,e)=>{
            var parent = $(e.parent.parent);
            let artist =parent.find('.artist').text().trim().split('/');
            var obj = {
                chartId,
                chartType,
                position:parseInt($(e).text()),
                lastWeek:parseInt(parent.find('.last-week').text().trim())||-1,
                cover:parent.find('.cover img').attr('src'),
                title:parent.find('.title').text().trim(),
                artist,
                peak:parseInt(parent.find('td').eq(3).text()),
                weekOn:parseInt(parent.find('td').eq(4).text())
            }
            charts.push(obj)
        })
        res.send({prev,next,charts})
    }).catch(error=>{
        res.send({error:500})
    });
})

router.post('/',(req,res) =>{
    var query = new AV.Query(Chart);
    for(let key in req.body.query){
        if(key == 'title'){
            query.contains(key,req.body.query[key]);
        }else if(key == 'artist'){
            query.containsAll(key,req.body.query[key]);
        }else {
            query.equalTo(key,req.body.query[key]);
        }
    }
    query.addAscending('chartId');
    query.addAscending('position');
    const pageSize = req.body.pageSize||40;
    const pageNo = req.body.pageNo||1;
    query.limit(pageSize);// 最多返回 10 条结果
    query.skip((pageNo-1)*pageSize);// 跳过 20 条结果
    query.find().then(results => {
        res.send({code:200,data:results})
    },error =>{
        res.send({code:500,message:'result not found'})
    })
})

module.exports = router